package huoye.shops.huoye.mine.activity;

import android.Manifest;
import android.app.DownloadManager;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.HandlerThread;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.codeideology.android.previewimage.PrevieImage;
import com.codeideology.android.previewimage.PrevieImageActivity;
import com.codeideology.android.utils.BarUtils;
import com.codeideology.android.utils.StringUtils;
import com.codeideology.android.widget.recycler.RecyclerViewAdapter;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import huoye.shops.MainActivity;
import huoye.shops.R;
import huoye.shops.base.APIUrls;
import huoye.shops.base.BaseTakePhotoActivity;
import huoye.shops.base.UserManager;
import huoye.shops.common.AddPictureAdapter;
import huoye.shops.common.ImageTextAdapter;
import huoye.shops.common.model.OssImageData;
import huoye.shops.huoye.mine.model.ShopDetials;
import huoye.shops.huoye.mine.model.detialsImg;
import huoye.shops.huoye.mine.presenter.EditShopMessagePresenter;
import huoye.shops.huoye.mine.view.IEditShopMessageView;
import huoye.shops.huoye.operation.model.AddImage;
import huoye.shops.huoye.operation.model.Descript;


public class EditShopMessageActivity extends BaseTakePhotoActivity implements IEditShopMessageView, TencentLocationListener {

    @BindView(R.id.edit_shop_message_et_shop_name)
    EditText etShopName;
    @BindView(R.id.edit_shop_message_et_contact)
    EditText etContact;
    @BindView(R.id.edit_shop_message_et_tel)
    EditText etTel;

    @BindView(R.id.edit_shop_message_tv_map_message)
    EditText etMapMessage;


    @BindView(R.id.edit_shop_message_rv_shop_photo)
    RecyclerView rvShopPhoto;
    @BindView(R.id.edit_shop_message_rv_shop_details)
    RecyclerView rvShopDetails;
    private ShopDetials shopDetials;
    private EditShopMessagePresenter mEditShopMessagePresenter;


    @BindView(R.id.edit_shop_message_iv_add_pic_logo)
    ImageView ivAddPicLogo;
    @BindView(R.id.edit_shop_message_iv_del_pic_logo)
    ImageView ivDelPicLogo;
    private String userShopId;


    @OnClick(R.id.edit_shop_message_iv_add_pic_logo)
    void onAddPicLogoClick() {
        isClickShopLogo = true;
        isClickShopPhoto = false;
        takePhoto();
    }


    @OnClick(R.id.edit_shop_message_iv_del_pic_logo)
    void onDelPicLogoClick() {
        mEditShopMessagePresenter.deleteOssImg(logoImg);
    }


    private String shopName;
    private String contactName;
    private String contactTel;
    private String logoImg = "";
    private List<String> faceImg = new ArrayList<>();
    private String province;
    private String city;
    private String area;
    private String address;

    private List<String> locations = new ArrayList<>();


    @OnClick(R.id.edit_shop_message_btn_save_message)
    void onSaveMessageClick() {
        shopName = etShopName.getText().toString();
        contactName = etContact.getText().toString();
        contactTel = etTel.getText().toString();
        address = etMapMessage.getText().toString();


        List<AddImage> images = shopPhotoAdapter.getData();
        if (shopPhotoAdapter != null || images != null || images.size() > 1) {
            for (AddImage image : images) {
                if (StringUtils.isNotEmpty(image.getImageUrl())) {
                    faceImg.add(image.getImageUrl());
                }
            }
        }

        List<Descript> data = imageTextAdapter.getData();
        if (imageTextAdapter != null || data != null || data.size() > 1) {
            for (int i = 0; i < data.size(); i++) {
                if (StringUtils.isNotEmpty(data.get(i).getImaPath())) {
                    data.get(i).setImgUrl(data.get(i).getImaPath());
                }
            }
        }

        if (!isAddLogo) {
            makeToast("请添加店铺Logo");
            return;
        }



        //移除省份和城市
        String noProvince = address.replace(province, "");
        String  correctAddress = noProvince.replace(city, "");

        Log.e("location===",correctAddress);
        Log.e("location===",province);
        Log.e("location===",city);
        Log.e("location===",area);

        mEditShopMessagePresenter.editShopInfo(shopName, contactName, contactTel,
                logoImg, faceImg, province, city,
                area, correctAddress, data,locations);
    }


    @OnClick(R.id.edit_shop_message_btn_location)
    void onLocationClick() {
        setLocation();
    }

    private void setLocation() {
        openPower();
        Log.e("location===","点击定位");
        startLocation();
    }



    private int REQ_LEVEL_GEO = 0; //包含经纬度
    private int REQ_LEVEL_NAME = 1; //	包含经纬度, 位置名称, 位置地址
    private int REQ_LEVEL_ADMIN_AREA = 3; //包含经纬度，位置所处的中国大陆行政区划
    private int REQ_LEVEL_POI = 4; //包含经纬度，位置所处的中国大陆行政区划及周边POI列表

    private void startLocation(){
        Log.e("location===","开始定位");
        TencentLocationRequest request = TencentLocationRequest.create();
        request.setInterval(100);
        request.setRequestLevel(REQ_LEVEL_ADMIN_AREA);
        mLocationManager.requestLocationUpdates(request, this);

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //可在此继续其他操作。
        startLocation();
    }




    @Override
    protected void onPause() {
        super.onPause();
        stopLocation();
    }

    private void stopLocation() {
        Log.e("location===","定位结束");
        mLocationManager.removeUpdates(this);
    }


    //位置回调接口
    @Override
    public void onLocationChanged(TencentLocation location, int error, String s) {
        Log.e("location===","开始定位"+error+"?"+s);

       if (error == TencentLocation.ERROR_OK) {
            locations.clear();
            // 定位成功
            etMapMessage.setText( location.getAddress());
            etMapMessage.requestFocus();
            etMapMessage.setSelection(etMapMessage.getText().length());

            province = location.getProvince();
            city = location.getCity();
            area = location.getDistrict();

        //    mLocationManager.removeUpdates(this);//停止定位
            Log.e("location===","aaaaa"+location.toString());
           locations.add(location.getLatitude()+"");
           locations.add(location.getLongitude()+"");

            stopLocation();
        } else {
            makeToast("定位失败 ");
            // "定位失败: " + reason;
        }


    }


    //状态回调
    @Override
    public void onStatusUpdate(String s, int i, String s1) {
        Log.e("location===","开始定位状态回调"+i+"?"+s1);
    }




    //打开定位权限
    private void openPower() {
        if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
            //如果没有授权，则请求授权
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1311);
            //String数组中为申请的权限，第一个是相机，第二个为修改内存，最后的参数即为申请授权的返回值，我设置的1311
        }
    }


    private int shopPhotoMax = 6;
    private AddPictureAdapter shopPhotoAdapter;
    private TencentLocationManager mLocationManager;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_edit_shop_message;
    }


    @Override
    protected void initView(@Nullable Bundle bundle) {
        shopDetials = getIntentData();
        setTitle("编辑");
        initUI();
        mEditShopMessagePresenter = new EditShopMessagePresenter();
        mEditShopMessagePresenter.addTaskListener(this);
        mEditShopMessagePresenter.onStart();


        mLocationManager = TencentLocationManager.getInstance(this);

        userShopId = UserManager.getInstance().getUserShopId();
        showShopDetailsAdapter();
        initializeRecyclerView();

        etMapMessage.setFilters(new InputFilter[]{new InputFilter.LengthFilter(100)}); //最大输入长度




    }

    private void initUI() {
        if (StringUtils.isNotEmpty(shopDetials.getShopName())) {
            etShopName.setText(shopDetials.getShopName());
            etShopName.setSelection(shopDetials.getShopName().length());//将光标移至文字末尾
        }
        etContact.setText(shopDetials.getContactName());
        etTel.setText(shopDetials.getContactTel());



        etMapMessage.setText(shopDetials.getJointAddress());






        province = shopDetials.getProvince();
        city = shopDetials.getCity();
        area = shopDetials.getArea();
        address = shopDetials.getAddress();
        logoImg = shopDetials.getShopLogo();
        if (StringUtils.isNotEmpty(logoImg)) {
            Glide.with(this)
                    .load(APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN + logoImg)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .placeholder(R.mipmap.ic_wait_logo)
                    .error(R.mipmap.ic_error)
                    .into(ivAddPicLogo);
            ivDelPicLogo.setVisibility(View.VISIBLE);
        }

        locations.add(shopDetials.getLatitude());
        locations.add(shopDetials.getLongitude());

    }







    private List<AddImage> AddImageList = new ArrayList<>();

    private void showShopDetailsAdapter() {
        shopPhotoAdapter = new AddPictureAdapter(this);
        List<detialsImg> faceImgs = shopDetials.getFaceImg();
        if (faceImgs.size() > 0) {
            for (int i = 0; i < faceImgs.size(); i++) {
                AddImage addImage = new AddImage();
                addImage.setImageUrl(faceImgs.get(i).getImgUrl());
                addImage.setLocal(false);
                AddImageList.add(addImage);
            }
            shopPhotoAdapter.setData(AddImageList);
        }
        shopPhotoAdapter.setMaxCount(shopPhotoMax);
        shopPhotoAdapter.setOnItemClickListener(new AddPictureAdapter.OnItemClickListener<AddImage>() {
            @Override
            public void onItemClick(AddImage addImage, int position, View view) {
                int count = shopPhotoAdapter.getItemCount();
                if (shopPhotoAdapter.getListCount() == shopPhotoMax) {
                    if (position == shopPhotoMax - 1) {
                        return;
                    }
                } else {
                    if (position == count - 1) {
                        isClickShopLogo = false;
                        isClickShopPhoto = true;
                        takePhoto();
                        return;
                    }
                }
                List<PrevieImage> images = new ArrayList<>();
                List<AddImage> data = shopPhotoAdapter.getData();
                for (int i = 0; i < data.size(); i++) {
                    PrevieImage image = new PrevieImage();
                    String url = APIUrls.COMMON_CONFIG.TYPE_COMMON_ALIYUN + data.get(i).getImageUrl();
                    image.setThumbnailUrl(url);
                    image.setImageViewWidth(view.getWidth());
                    image.setImageViewHeight(view.getHeight());
                    int[] points = new int[2];
                    view.getLocationInWindow(points);
                    image.setImageViewX(points[0]);
                    image.setImageViewY(points[1] - BarUtils.getStatusBarHeight(EditShopMessageActivity.this));
                    images.add(image);
                }
                PrevieImageActivity.onStartActivity(EditShopMessageActivity.this, (ArrayList<PrevieImage>) images, position);
            }
        });
        rvShopPhoto.setLayoutManager(new GridLayoutManager(this, 3));
        rvShopPhoto.setAdapter(shopPhotoAdapter);
    }


    //判断图文是否为空
    private boolean isNull() {
        List<Descript> list = imageTextAdapter.getData();
        for (int i = 0; i < list.size(); i++) {

            if (!StringUtils.isNotEmpty(list.get(i).getImgDes())) {
                makeToast("请填写商店描述");
                return false;
            }

            if (!StringUtils.isNotEmpty(list.get(i).getImgUrl())) {
                makeToast("请选择商店详情图片");
                return false;
            }

        }
        return true;
    }


    List<Descript> imageTextList = new ArrayList<>();

    private void initData() {
        if (shopDetials.getDetialsImg().size() == 0) {
            for (int i = 0; i < 1; i++) {
                imageTextList.add(new Descript());
            }
        } else {
            List<detialsImg> detialsImg = shopDetials.getDetialsImg();
            for (int i = 0; i < detialsImg.size(); i++) {
                Descript descript = new Descript();
                descript.setImgDes(detialsImg.get(i).getImgDes());
                descript.setImgUrl(detialsImg.get(i).getImgUrl());
                descript.setLocal(false);
                imageTextList.add(descript);
            }
        }
    }

    private void addData() {
        if (imageTextAdapter != null) {
            imageTextAdapter.getData().add(new Descript());
            imageTextAdapter.notifyDataSetChanged();
        }
    }


    private boolean isClickShopLogo;
    private boolean isClickShopPhoto;

    private int mPosition;
    private int imageTextMax = 100;
    private ImageTextAdapter imageTextAdapter;

    private void initializeRecyclerView() {
        imageTextAdapter = new ImageTextAdapter(this);
        initData();
        imageTextAdapter.setData(imageTextList);
        imageTextAdapter.setMaxCount(imageTextMax);
        imageTextAdapter.setOnItemClickListener(new ImageTextAdapter.OnItemClickListener<Descript>() {
            @Override
            public void onItemClick(Descript list, int i, View view) {
                int count = imageTextAdapter.getItemCount();
                if (imageTextAdapter.getListCount() == imageTextMax) {
                    if (i == imageTextMax - 1) {
                        return;
                    }
                } else {
                    if (i == count - 1) {
                        boolean b = isNull();
                        if (b) {
                            addData();
                        }
                        return;
                    }
                }
            }

            @Override
            public void onAddImageClick(int position) {
                isClickShopLogo = false;
                isClickShopPhoto = false;
                mPosition = position;
                takePhoto();
            }
        });
        rvShopDetails.setLayoutManager(new LinearLayoutManager(this));
        rvShopDetails.setAdapter(imageTextAdapter);

    }

    private String imgPath = "";
    private String imgPhotoPath = "";
    private String imgDescriptPath = "";

    @Override
    public void takeSuccess(TResult result) {
        if (result != null) {
            TImage image = result.getImage();
            //上传单张图片
            if (isClickShopLogo) {
                imgPath = image.getCompressPath();
                File file = new File(imgPath);
                mEditShopMessagePresenter.uploadOssImg(userShopId, "shop", imgPath);
                Glide.with(this)
                        .load(Uri.fromFile(file))
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .placeholder(R.mipmap.ic_wait_logo)
                        .error(R.mipmap.ic_error)
                        .into(ivAddPicLogo);
                ivDelPicLogo.setVisibility(View.VISIBLE);
            } else {
                if (isClickShopPhoto) {
                    AddImage img = new AddImage();
                    imgPhotoPath = image.getCompressPath();
                    mEditShopMessagePresenter.uploadOssImg(userShopId, "shop", imgPhotoPath);
                    img.setPath(imgPhotoPath);
                    img.setLocal(true);
                    if (shopPhotoAdapter.getListCount() == 0) {
                        shopPhotoAdapter.add(0, img);
                    } else {
                        shopPhotoAdapter.add(shopPhotoAdapter.getListCount(), img);
                    }
                    shopPhotoAdapter.notifyDataSetChanged();
                } else {
                    imgDescriptPath = image.getCompressPath();
                    mEditShopMessagePresenter.uploadOssImg(userShopId, "shop", imgDescriptPath);
                    imageTextAdapter.getData().get(mPosition).setImgUrl(imgDescriptPath);
                    imageTextAdapter.getData().get(mPosition).setLocal(true);
                    imageTextAdapter.notifyDataSetChanged();
                }
            }


        }
    }


    @Override
    public void setUploadMore(List<OssImageData> ossImageData) {

    }


    @Override
    public void setUpload(OssImageData ossImageData) {

        if (isClickShopLogo) {
            logoImg = ossImageData.getFilePath();
            isAddLogo = true;
        } else {
            if (isClickShopPhoto) {
                List<AddImage> images = shopPhotoAdapter.getData();
                if (shopPhotoAdapter == null || images == null || images.size() < 1) {
                    return;
                }
                for (AddImage image : images) {
                    if (image.getPath().equals(imgPhotoPath)) {
                        image.setImageUrl(ossImageData.getFilePath());
                    }
                }

            } else {

                List<Descript> images = imageTextAdapter.getData();
                if (imageTextAdapter == null || images == null || images.size() < 1) {
                    return;
                }
                for (Descript image : images) {
                    if (image.getImgUrl().equals(imgDescriptPath)) {
                        image.setImaPath(ossImageData.getFilePath());
                    }
                }

            }
        }


    }

    private boolean isAddLogo = true;

    @Override
    public void setDelImage() {
        ivAddPicLogo.setImageResource(R.mipmap.ic_add_image);
        ivDelPicLogo.setVisibility(View.GONE);
        isAddLogo = false;
    }



}
